package com.yayawan.laomigame.callback;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;


import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.yayawan.laomigame.utils.UriUtils;
import com.yayawan.utils.Yayalog;
import com.ycbjie.webviewlib.base.X5WebChromeClient;
import com.ycbjie.webviewlib.utils.X5LogUtils;
import com.ycbjie.webviewlib.utils.X5WebUtils;

import java.io.File;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class X5WebChromeClientNew extends X5WebChromeClient {

    Activity mActivity;
    /**
     * 构造方法
     *
     * @param webView
     * @param context 上下文
     */
    public X5WebChromeClientNew(WebView webView, Context context) {
        super(webView, context);

       // mcontext=context;
    }
    /**
     * 构造方法
     *
     * @param webView
     * @param context 上下文
     */
    public X5WebChromeClientNew(WebView webView,Activity activity,Context context) {
        super(webView, context);

        mActivity=activity;
    }


    /**
     * 打开文件夹
     * @param uploadMsg                         msg
     */
    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        Yayalog.loger("jinlai le openFileChooserImpl");
    }
    /**
     * 为'<input type="file" />'显示文件选择器，返回false使用默认处理
     * For Android > 5.0
     * @param webView                           webview
     * @param uploadMsg                         msg
     * @param fileChooserParams                 参数
     * @return
     */
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg,
                                     FileChooserParams fileChooserParams) {
        X5LogUtils.i("-------jiafan onShowFileChooser-------");
        //openFileChooserImplForAndroid5(uploadMsg);
        return true;
    }
    ValueCallback<Uri[]> mUploadMessageForAndroid5;




    public static Uri getMediaUriFromPath(Context context, String path) {
        Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = context.getContentResolver().query(mediaUri,
                null,
                MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                new String[] {path.substring(path.lastIndexOf("/") + 1)},
                null);

        Uri uri = null;
         Uri contentUri = null;
        if(cursor.moveToFirst()) {
            uri = ContentUris.withAppendedId(mediaUri,
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
             contentUri = ContentUris.withAppendedId(Uri.parse("content://com.android.providers.media.documents/document/image:"),
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        }
        cursor.close();
        return contentUri;
    }
    // 压缩图片url
    private Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;// 压缩好比例大小后再进行质量压缩
    }
    public Uri getUriFromPath2(String path){
        Uri uri = null;
        if (path != null) {
            path = Uri.decode(path);
            // Log.d(TAG, "path2 is " + path);
            Yayalog.loger("path2 is " + path);
            ContentResolver cr = mActivity.getContentResolver();StringBuffer buff = new StringBuffer();
            buff.append("(")
                    .append(MediaStore.Images.ImageColumns.DATA)
                    .append("=")
                    .append("'" + path + "'")
                    .append(")");
            Cursor cur = cr.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.ImageColumns._ID},
                    buff.toString(), null, null);
            int index = 0;
            for (cur.moveToFirst(); !cur.isAfterLast(); cur
                    .moveToNext()) {
                index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                // set _id value
                index = cur.getInt(index);
            }
            if (index == 0) {
                //do nothing
            } else {
                Uri uri_temp = Uri
                        .parse("content://media/external/images/media/"
                                + index);
                Yayalog.loger("uri_temp is " + uri_temp);
                // Log.d(, "uri_temp is " + uri_temp);
                //Yayalog.loger("uri_temp is " + uri_temp);
                if (uri_temp != null) {
                    uri = uri_temp;
                }
            }
        }
        return uri;
    }
    public Uri getUriFromPath(String path){
        Uri uri = null;
        if (path != null) {
            path = Uri.decode(path);
            // Log.d(TAG, "path2 is " + path);
            Yayalog.loger("path2 is " + path);
            ContentResolver cr = mActivity.getContentResolver();
            StringBuffer buff = new StringBuffer();
            buff.append("(")
                    .append(MediaStore.Images.ImageColumns.DATA)
                    .append("=")
                    .append("'" + path + "'")
                    .append(")");
            Cursor cur = cr.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.ImageColumns._ID},
                    buff.toString(), null, null);
            int index = 0;
            for (cur.moveToFirst(); !cur.isAfterLast(); cur
                    .moveToNext()) {
                index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                // set _id value
                index = cur.getInt(index);
            }
            if (index == 0) {
                //do nothing
            } else {
                Uri uri_temp = Uri
                        .parse("content://media/external/images/media/"
                                + index);
                Yayalog.loger("uri_temp is " + uri_temp);
                // Log.d(, "uri_temp is " + uri_temp);
                //Yayalog.loger("uri_temp is " + uri_temp);
                if (uri_temp != null) {
                    uri = uri_temp;
                }
            }
        }
        return uri;
    }
    /**
     * 5.0以上 上传图片成功后的回调
     */
    public void uploadMessageForAndroid5(Intent intent, int resultCode) {
        Yayalog.loger("new=========uploadMessageForAndroid5 ：" );
        if (null == mUploadMessageForAndroid5) {
            Yayalog.loger("uploadMessageForAndroid5 is null ：" );
            return;
        }
        Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
        if (result != null) {
            Yayalog.loger("uploadMessageForAndroid5 正在上传：" );
            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
        } else {
            Yayalog.loger("uploadMessageForAndroid5 正在上传：" );
            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
        }
        mUploadMessageForAndroid5 = null;
    }
}
